package com.itheima.aop;

import com.itheima.domain.Equipment;
import com.itheima.domain.SysLog;
import com.itheima.mapper.SysLogMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Date;

@Component
@Aspect
public class EquipmentInfoAop {


    @Autowired
    private SysLogMapper sysLogMapper;


    /**
     * 切入点表达式
     */
    @Pointcut("execution(* com.itheima.service.impl.EquipmentServiceImpl.add*(..))")
    public void pt(){}


    /**
     * 通知方法
     */
    @Around("pt()")
    public Object around(ProceedingJoinPoint pjp) {
        System.out.println("我打印了.....");
        Object proceed = null;
        try {
            //1.获取方法的参数
            Object[] args = pjp.getArgs();
            //2.给方法的参数添加createTime  updateTime 的数据
            Equipment equipment = (Equipment) args[0];
            equipment.setUpdated(new Date());
            equipment.setCreated(new Date());
            //3.执行方法
             proceed = pjp.proceed(args);
            return proceed;
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            //todo 添加日志记录
            SysLog log = new SysLog();
            log.setUsername("admin");
            log.setMethod(pjp.getSignature().getDeclaringTypeName()+"."+pjp.getSignature().getName());
            log.setParams(Arrays.toString(pjp.getArgs()));
            log.setCreated(new Date());
            log.setOperation(pjp.getSignature().getName());
            //todo 调用mapper 存储到 数据库即可
            sysLogMapper.add(log);
            System.out.println("添加日志到数据库:"+log);
        }
        return proceed;
    }
}
